package GUILayer;

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
import ControlLayer.SalesCtr;
import ModelLayer.RealException;
import ModelLayer.Sale;
import ModelLayer.SalesLine;
import ModelLayer.SalesRecords;
import ModelLayer.Status;

public class OfferUI extends JPanel {

	/**
	 * Create the panel.
	 */
	private static final long serialVersionUID = 1L;
	private SalesCtr saleCtr;
	private SaleUI saleUI;

	private JPanel offerPanel;
	private JPanel showAllOffersPanel;
	private JPanel showOfferPanel;
	private JPanel showOfferLeftPanel;
	private JPanel showOfferRightPanel;
	private JPanel offerInfoPanel;
	private JPanel offerChoicePanel;
	private JPanel editOfferPanel;
	private JPanel editSalelinePanel;
	private JPanel salelineChoicePanel;
	private JPanel createOfferPanel;
	private JPanel createOfferLeftPanel;
	private JPanel createOfferRightPanel;

	private JLabel lblOfferIdOfferInfo = new JLabel("Offer Id:");
	private JLabel lblCustomerId = new JLabel("Customer Id:");
	private JLabel lblEmployeeId = new JLabel("Employee Id:");
	private JLabel lblDate = new JLabel("Date(dd/mm/yyyy)");
	private JLabel lblDeliveryAddress = new JLabel("Delivery Address:");
	private JLabel lblPickup = new JLabel("Self Pick Up:");

	private JRadioButton rbnPickupYes;
	private JRadioButton rbnPickupNo;

	private ButtonGroup bgPickup = new ButtonGroup();

	private JTextField textField_offerIdMenu = new JTextField();
	private JTextField textField_offerIdOrderInfo = new JTextField();
	private JTextField textField_customerId;
	private JTextField textField_employeeId;
	private JTextField textField_date;
	private JTextField textField_deliveryAddress;
	private JTextField textField_ProductBarcode;
	private JTextField textField_ProductQuantity;

	private JButton btnSearchOffer;
	private JButton btnCreateOfferMenu;
	private JButton btnSaveOffer;
	private JButton btnConfirmOffer;
	private JButton btnCreateOffer;
	private JButton btnAddSaleline;
	private JButton btnDeleteSaleline;

	private DefaultTableModel offerTableModel;
	private DefaultTableModel saleLineTableModel;
	private JTable showAllOffersTable;
	private JTable showSalelineTable;
	private JScrollPane offerTableScrollPane;
	private JScrollPane salelineScrollPane;
	private JPanel editOfferLeftPanel;
	private JPanel editOfferRightPanel;
	private JPanel offerMenuLeftPanel;
	private String loggedInPosition;

	public OfferUI(SaleUI saleUI) {
		saleCtr = new SalesCtr();
		this.saleUI = saleUI;
		initialize();

	}

	public void initialize() {

		loggedInPosition = LoginUI.getLoggedInPosition();

		this.setLayout(new BorderLayout());

		// make offer top menu with search function
		JPanel offerMenuPanel = new JPanel();
		offerMenuPanel.setLayout(new BorderLayout());
		offerMenuPanel
				.setBorder(BorderFactory.createTitledBorder("Offer Menu"));
		this.add(offerMenuPanel, BorderLayout.NORTH);

		JLabel lblOfferIdMenu = new JLabel("Offer Id:");

		textField_offerIdMenu.setColumns(8);
		btnSearchOffer = new JButton("Search");
		btnSearchOffer.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				int offerId;
				try {
					offerId = Integer.parseInt(textField_offerIdMenu.getText());
					if (showOffer(offerId)) {
					}
				} catch (NumberFormatException e1) {
					JOptionPane.showMessageDialog(null, "Please input number",
							"Error", JOptionPane.ERROR_MESSAGE);
					textField_offerIdMenu.setText("");
				}
			}
		});
		offerMenuLeftPanel = new JPanel();
		offerMenuLeftPanel.setLayout(new FlowLayout());
		offerMenuPanel.add(offerMenuLeftPanel, BorderLayout.WEST);
		JPanel offerMenuRightPanel = new JPanel();
		offerMenuRightPanel.setLayout(new FlowLayout());
		offerMenuPanel.add(offerMenuRightPanel, BorderLayout.EAST);
		offerMenuRightPanel.add(lblOfferIdMenu);
		offerMenuRightPanel.add(textField_offerIdMenu);
		offerMenuRightPanel.add(btnSearchOffer);
		
		if (loggedInPosition.equals("admin")
				|| loggedInPosition.equals("salesman")) {
			btnCreateOfferMenu = new JButton("Create Offer");
			btnCreateOfferMenu.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					createOffer();
					textField_deliveryAddress.setEditable(false);
					rbnPickupYes.setSelected(true);
				}
			});
			offerMenuLeftPanel.add(btnCreateOfferMenu);
		}

		// add panels in orderPanel card layout
		offerPanel = new JPanel();
		offerPanel.setLayout(new CardLayout());
		this.add(offerPanel, BorderLayout.CENTER);

		showAllOffersPanel = new JPanel();
		offerPanel.add("showAllOffersPanel", showAllOffersPanel);
		showAllOffersPanel.setLayout(new BoxLayout(showAllOffersPanel,
				BoxLayout.X_AXIS));
		showAllOffersPanel.setBorder(BorderFactory
				.createTitledBorder("All Offers"));

		// make show all offers table
		addOfferTable();
		showAllOffers();

		// make show offer panel
		showOfferPanel = new JPanel();
		offerPanel.add("showOfferPanel", showOfferPanel);
		showOfferPanel.setLayout(new GridLayout(1, 2));

		showOfferLeftPanel = new JPanel();
		showOfferLeftPanel.setLayout(new BoxLayout(showOfferLeftPanel,
				BoxLayout.Y_AXIS));

		showOfferRightPanel = new JPanel();
		showOfferRightPanel.setLayout(new BoxLayout(showOfferRightPanel,
				BoxLayout.X_AXIS));
		showOfferRightPanel.setBorder(BorderFactory
				.createTitledBorder("SaleLines"));

		showOfferPanel.add(showOfferLeftPanel);
		showOfferPanel.add(showOfferRightPanel);

		// make edit offerInfo Panel
		editOfferPanel = new JPanel();
		editOfferPanel
				.setBorder(BorderFactory.createTitledBorder("Edit Offer"));
		offerPanel.add("editOfferInfoPanel", editOfferPanel);
		editOfferPanel.setLayout(new GridLayout(0, 2, 0, 0));

		editOfferLeftPanel = new JPanel();
		editOfferPanel.add(editOfferLeftPanel);
		editOfferLeftPanel.setLayout(new BoxLayout(editOfferLeftPanel,
				BoxLayout.Y_AXIS));

		editOfferRightPanel = new JPanel();
		editOfferPanel.add(editOfferRightPanel);
		editOfferRightPanel.setLayout(new BoxLayout(editOfferRightPanel,
				BoxLayout.X_AXIS));

		// make edit-saleline table panel and edit-saleline choice panel
		editSalelinePanel = new JPanel();
		editSalelinePanel.setBorder(BorderFactory
				.createTitledBorder("Edit Offer SaleLine"));
		editSalelinePanel.setLayout(new BoxLayout(editSalelinePanel,
				BoxLayout.Y_AXIS));
		// offerPanel.add("editSalelinePanel", editSalelinePanel);

		editOfferRightPanel.add("editSalelinePanel", editSalelinePanel);

		salelineChoicePanel = new JPanel();
		salelineChoicePanel.setLayout(new FlowLayout());

		// make create offer panel
		createOfferPanel = new JPanel();
		createOfferPanel.setLayout(new GridLayout(1, 2));

		// make create offer left panel

		createOfferLeftPanel = new JPanel();
		createOfferLeftPanel.setLayout(new BoxLayout(createOfferLeftPanel,
				BoxLayout.Y_AXIS));
		createOfferRightPanel = new JPanel();
		createOfferRightPanel.setLayout(new BoxLayout(createOfferRightPanel,
				BoxLayout.Y_AXIS));
		createOfferRightPanel.setBorder(BorderFactory
				.createTitledBorder("SaleLine"));

		createOfferPanel.add(createOfferLeftPanel);
		createOfferPanel.add(createOfferRightPanel);
		offerPanel.add("createOfferPanel", createOfferPanel);

	}

	private void createOffer() {
		createOfferLeftPanel.removeAll();

		// add offerInfoPanel
		JPanel offerInfoPanel = createOfferInfoPanel();
		setOfferInfoEditable(true);

		int newOfferId = Sale.getLastId() + 1;
		textField_offerIdOrderInfo.setText(Integer.toString(newOfferId));
		textField_date.setText(convertDate(getCurrentDate()));
		textField_date.setEditable(false);
		textField_employeeId.setText(String.valueOf(LoginUI.getLoggedInId()));
		textField_employeeId.setEditable(false);

		createOfferLeftPanel.add(offerInfoPanel);

		// add offer choice panel
		JPanel createOfferChoicePanel = new JPanel();
		createOfferChoicePanel.setLayout(new FlowLayout());
		createOfferLeftPanel.add(createOfferChoicePanel);

		JButton btnCancelCreateOffer = new JButton("Cancel");
		btnCancelCreateOffer.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				showAllOffers();
				textField_offerIdMenu.setText("");
			}
		});
		btnCreateOffer = new JButton("Create");
		btnCreateOffer.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {

				try {
					try {
						saleCtr.createOffer(
								Integer.parseInt(textField_customerId.getText()),
								Integer.parseInt(textField_employeeId.getText()),
								getCurrentDate());
						textField_offerIdMenu
								.setText(textField_offerIdOrderInfo.getText());
					} catch (NumberFormatException e1) {
						JOptionPane.showMessageDialog(null,
								"Please input number", "Error",
								JOptionPane.ERROR_MESSAGE);
					}
					if (rbnPickupYes.isSelected()) {
						saleCtr.hasPickup(Integer
								.parseInt(textField_offerIdOrderInfo.getText()));
					} else {
						saleCtr.noPickup(
								Integer.parseInt(textField_offerIdOrderInfo
										.getText()), textField_deliveryAddress
										.getText());
					}
					JOptionPane
							.showMessageDialog(
									null,
									"The offer is created, please continue to saleline.",
									"Create Offer",
									JOptionPane.INFORMATION_MESSAGE);
					btnSaveOffer.setEnabled(true);
					btnConfirmOffer.setEnabled(true);
					btnAddSaleline.setEnabled(true);
					btnDeleteSaleline.setEnabled(true);
					btnCreateOffer.setEnabled(false);
					setOfferInfoEditable(false);
				} catch (RealException e1) {
					JOptionPane.showMessageDialog(null, e1.getError(), "Error",
							JOptionPane.ERROR_MESSAGE);
				}
			}
		});
		btnSaveOffer = new JButton("Save");
		btnSaveOffer.setEnabled(false);
		btnSaveOffer.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				showAllOffers();
				textField_offerIdMenu.setText("");
			}
		});
		btnConfirmOffer = new JButton("Confirm");
		btnConfirmOffer.setEnabled(false);
		btnConfirmOffer.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				confirmOfferActionPerformed(e);
				showAllOffers();
				textField_offerIdMenu.setText("");
			}
		});
		createOfferChoicePanel.add(btnCancelCreateOffer);
		createOfferChoicePanel.add(btnCreateOffer);
		createOfferChoicePanel.add(btnSaveOffer);
		createOfferChoicePanel.add(btnConfirmOffer);

		// add saleline table
		createOfferRightPanel.removeAll();

		salelineScrollPane = showSalelineTable();
		JPanel showSalelinePanel = new JPanel();
		showSalelinePanel.setLayout(new BoxLayout(showSalelinePanel,
				BoxLayout.X_AXIS));
		showSalelinePanel.add(salelineScrollPane);
		createOfferRightPanel.add(showSalelinePanel);

		// add saleline choice panel
		JPanel salelineChoicePanel = new JPanel();
		salelineChoicePanel.setLayout(new FlowLayout());
		createOfferRightPanel.add(salelineChoicePanel);

		btnAddSaleline = new JButton("Add");
		btnAddSaleline.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				EventQueue.invokeLater(new Runnable() {
					public void run() {
						try {
							JFrame addSalelineFrame = addSalelinePopupWindow();
							addSalelineFrame.setVisible(true);
						} catch (Exception e) {
							e.printStackTrace();
						}

					}
				});

			}
		});
		btnAddSaleline.setEnabled(false);
		btnDeleteSaleline = new JButton("Delete");
		btnDeleteSaleline.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				EventQueue.invokeLater(new Runnable() {
					public void run() {
						try {
							JFrame deleteSalelineFrame = deleteSalelinePopupWindow();
							deleteSalelineFrame.setVisible(true);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				});
			}
		});
		btnDeleteSaleline.setEnabled(false);
		salelineChoicePanel.add(btnAddSaleline);
		salelineChoicePanel.add(btnDeleteSaleline);

		CardLayout cl = (CardLayout) offerPanel.getLayout();
		cl.show(offerPanel, "createOfferPanel");
	}

	private boolean showOffer(int offerId) {
		boolean success = true;
		Sale offer = null;
		try {
			if (offerId != 0) {
				offer = saleCtr.getOffer(offerId);
			}
		} catch (NumberFormatException e) {
			success = false;
			JOptionPane.showMessageDialog(null, "Please input Number", "Error",
					JOptionPane.ERROR_MESSAGE);
			return success;
		} catch (RealException e) {
			success = false;
			JOptionPane.showMessageDialog(null, e.getError(), "Error",
					JOptionPane.ERROR_MESSAGE);
			return success;
		}
		if (success) {
			offerInfoPanel = createOfferInfoPanel();

			showOfferLeftPanel.removeAll();
			showOfferLeftPanel.add(offerInfoPanel);
			offerChoicePanel = createOfferChoicePanel();
			showOfferLeftPanel.add(offerChoicePanel);

			showOfferRightPanel.removeAll();
			showOfferRightPanel.add(showSalelineTable());

			setOfferInfo(offer);

			ArrayList<SalesLine> saleLines = offer.getSaleLines();
			saleLineTableModel.setRowCount(0);
			for (SalesLine saleline : saleLines) {
				saleLineTableModel.addRow(new Object[] { saleline.getBarcode(),
						saleline.getSaleItem().getName(),
						saleline.getQuantity(),
						saleline.getSaleItem().getsPrice(),
						saleline.getSaleItem().getTax(),
						saleline.getSubtotalWithoutDiscount() });
			}

			addTotalPrice(offerId, saleLineTableModel);
		}
		CardLayout cl = (CardLayout) offerPanel.getLayout();
		cl.show(offerPanel, "showOfferPanel");
		return success;

	}

	private void setOfferInfo(Sale offer) {
		textField_offerIdOrderInfo.setText(Integer.toString(offer.getId()));
		textField_customerId.setText(Integer.toString(offer.getCustomer()
				.getId()));
		textField_employeeId.setText(Integer.toString(offer.getEmployee()
				.getId()));
		textField_date.setText(offer.getDate());
		if (offer.getPickup()) {
			rbnPickupYes.setSelected(true);
		} else {
			rbnPickupNo.setSelected(true);
			textField_deliveryAddress.setText(offer.getdAddress());
		}
	}

	private JPanel createOfferInfoPanel() {
		JPanel offerInfoPanel = new JPanel();
		offerInfoPanel
				.setBorder(BorderFactory.createTitledBorder("Offer Info"));
		GroupLayout gl = new GroupLayout(offerInfoPanel);
		offerInfoPanel.setLayout(gl);
		gl.setAutoCreateGaps(true);
		gl.setAutoCreateContainerGaps(true);

		// textField_offerIdOrderInfo = new JTextField();
		textField_customerId = new JTextField();
		textField_employeeId = new JTextField();
		textField_date = new JTextField();
		textField_deliveryAddress = new JTextField();

		textField_offerIdOrderInfo.setColumns(8);
		textField_customerId.setColumns(8);
		textField_employeeId.setColumns(8);
		textField_date.setColumns(8);
		textField_deliveryAddress.setColumns(8);

		rbnPickupYes = new JRadioButton("Yes");

		rbnPickupNo = new JRadioButton("No");
		rbnPickupYes.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				textField_deliveryAddress.setEditable(false);
				textField_deliveryAddress.setText("");
			}
		});
		rbnPickupNo.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				textField_deliveryAddress.setEditable(true);
			}
		});
		bgPickup.add(rbnPickupYes);
		bgPickup.add(rbnPickupNo);

		gl.setHorizontalGroup(gl
				.createSequentialGroup()
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.LEADING)
								.addComponent(lblOfferIdOfferInfo)
								.addComponent(lblCustomerId)
								.addComponent(lblEmployeeId)
								.addComponent(lblDate)
								.addComponent(lblDeliveryAddress)
								.addComponent(lblPickup))
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.LEADING)
								.addComponent(textField_offerIdOrderInfo)
								.addComponent(textField_customerId)
								.addComponent(textField_employeeId)
								.addComponent(textField_date)
								.addComponent(textField_deliveryAddress)
								.addComponent(rbnPickupYes)
								.addComponent(rbnPickupNo)));
		gl.setVerticalGroup(gl
				.createSequentialGroup()
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.BASELINE)
								.addComponent(lblOfferIdOfferInfo)
								.addComponent(textField_offerIdOrderInfo))
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.BASELINE)
								.addComponent(lblCustomerId)
								.addComponent(textField_customerId))
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.BASELINE)
								.addComponent(lblEmployeeId)
								.addComponent(textField_employeeId))
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.BASELINE)
								.addComponent(lblDate)
								.addComponent(textField_date))
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.BASELINE)
								.addComponent(lblDeliveryAddress)
								.addComponent(textField_deliveryAddress))
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.BASELINE)
								.addComponent(lblPickup)
								.addComponent(rbnPickupYes))
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.LEADING)
								.addComponent(rbnPickupNo)));

		textField_offerIdOrderInfo.setEditable(false);
		setOfferInfoEditable(false);
		return offerInfoPanel;
	}

	private void setOfferInfoEditable(boolean editable) {

		textField_customerId.setEditable(editable);
		textField_employeeId.setEditable(editable);
		textField_date.setEditable(editable);
		textField_deliveryAddress.setEditable(rbnPickupNo.isSelected());
		rbnPickupYes.setEnabled(editable);
		rbnPickupNo.setEnabled(editable);
	}

	private JPanel creatOfferEditChoicePanel() {
		JPanel offerEditChoicePanel = new JPanel();
		offerEditChoicePanel.setLayout(new FlowLayout());
		JButton btnSaveOfferInfo = new JButton("Save");
		btnSaveOfferInfo.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				// whether successfully save info and goto edit saleline panel
				if (saveOfferInfo(Integer.parseInt(textField_offerIdMenu
						.getText()))) {
					showOffer(getTextFieldId(textField_offerIdMenu));
				}
			}
		});
		JButton btnCancelOfferInfo = new JButton("Cancel");
		btnCancelOfferInfo.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				showOffer(getTextFieldId(textField_offerIdOrderInfo));

			}
		});
		offerEditChoicePanel.add(btnSaveOfferInfo);
		offerEditChoicePanel.add(btnCancelOfferInfo);
		return offerEditChoicePanel;

	}

	// edit offer saleline
	private void editOfferSaleline(int offerId) {
		// add saleline table
		// offerid = offerId;
		JScrollPane salelineTableEditScrollPane = showSalelineTable();
		editSalelinePanel.removeAll();
		editSalelinePanel.add(salelineTableEditScrollPane);
		showOfferSaleline(offerId);

		// add saleline choice panel
		editSalelinePanel.add(salelineChoicePanel);
		JButton btnAddSaleline = new JButton("Add");
		btnAddSaleline.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {

				EventQueue.invokeLater(new Runnable() {
					public void run() {
						try {
							JFrame addSalelineFrame = addSalelinePopupWindow();
							addSalelineFrame.setVisible(true);
						} catch (Exception e) {
							e.printStackTrace();
						}

					}
				});
			}
		});
		JButton btnDeleteSaleline = new JButton("Delete");
		btnDeleteSaleline.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				EventQueue.invokeLater(new Runnable() {
					public void run() {
						try {
							JFrame deleteSalelineFrame = deleteSalelinePopupWindow();
							deleteSalelineFrame.setVisible(true);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				});
			}
		});
		salelineChoicePanel.removeAll();
		salelineChoicePanel.add(btnAddSaleline);
		salelineChoicePanel.add(btnDeleteSaleline);

		CardLayout cl = (CardLayout) offerPanel.getLayout();
		cl.show(offerPanel, "editSalelinePanel");

	}

	public JFrame addSalelinePopupWindow() {
		final JFrame addSalelinePupupWindow = new JFrame("Add SaleLine");
		addSalelinePupupWindow.setSize(450, 100);
		addSalelinePupupWindow.setLocationRelativeTo(null);
		JLabel productBarcode = new JLabel("Product Barcode:");
		JLabel productQuantity = new JLabel("Quantity:");
		textField_ProductBarcode = new JTextField();
		textField_ProductBarcode.setColumns(8);
		textField_ProductQuantity = new JTextField();
		textField_ProductQuantity.setColumns(8);
		JButton btnAddSalelineOK = new JButton("OK");
		btnAddSalelineOK.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				int offerId = Integer.parseInt(textField_offerIdMenu.getText());
				String barcode = textField_ProductBarcode.getText();

				try {
					int quantity = Integer.parseInt(textField_ProductQuantity
							.getText());
					saleCtr.addSalesLine(offerId, quantity, barcode);
					showOfferSaleline(offerId);

					showSalelineTable.revalidate();
					showSalelineTable.repaint();
					addSalelinePupupWindow.dispose();
				} catch (NumberFormatException e1) {
					JOptionPane.showMessageDialog(null,
							"Please input product barcode and quantity.",
							"Error", JOptionPane.ERROR_MESSAGE);
				} catch (RealException e1) {
					JOptionPane.showMessageDialog(null, e1.getError(), "Error",
							JOptionPane.ERROR_MESSAGE);
				} catch (HeadlessException e1) {

				}
			}
		});
		JButton btnAddSalelineCancel = new JButton("Cancel");
		btnAddSalelineCancel.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				addSalelinePupupWindow.dispose();
			}
		});

		JPanel addSalelinePanel = new JPanel();
		addSalelinePanel.setLayout(new BoxLayout(addSalelinePanel,
				BoxLayout.Y_AXIS));
		JPanel addSalelineInfoPanel = new JPanel();
		addSalelineInfoPanel.setLayout(new FlowLayout());
		JPanel addSalelineChoicePanel = new JPanel();
		addSalelineChoicePanel.setLayout(new FlowLayout());

		addSalelinePupupWindow.getContentPane().add(addSalelinePanel);
		addSalelinePanel.add(addSalelineInfoPanel);
		addSalelinePanel.add(addSalelineChoicePanel);
		addSalelineInfoPanel.add(productBarcode);
		addSalelineInfoPanel.add(textField_ProductBarcode);
		addSalelineInfoPanel.add(productQuantity);
		addSalelineInfoPanel.add(textField_ProductQuantity);
		addSalelineChoicePanel.add(btnAddSalelineOK);
		addSalelineChoicePanel.add(btnAddSalelineCancel);

		return addSalelinePupupWindow;
	}

	private JFrame deleteSalelinePopupWindow() {
		final JFrame deleteSalelineWindow = new JFrame("Delete SaleLine");
		deleteSalelineWindow.setSize(500, 100);
		deleteSalelineWindow.setLocationRelativeTo(null);
		JLabel productBarcode = new JLabel("Please input product barcode:");
		textField_ProductBarcode = new JTextField();
		textField_ProductBarcode.setColumns(8);
		JButton btnDeleteSalelineOK = new JButton("OK");
		btnDeleteSalelineOK.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				int offerId = Integer.parseInt(textField_offerIdMenu.getText());
				String barcode = textField_ProductBarcode.getText();
				try {
					saleCtr.removeSalesLine(offerId, barcode);
					showOfferSaleline(offerId);
					showSalelineTable.revalidate();
					showSalelineTable.repaint();
					deleteSalelineWindow.dispose();
				} catch (RealException e1) {
					JOptionPane.showMessageDialog(null, e1.getError(), "Error",
							JOptionPane.ERROR_MESSAGE);
				}

			}
		});
		JButton btnDeleteSalelineCancel = new JButton("Cancel");
		btnDeleteSalelineCancel.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				deleteSalelineWindow.dispose();
			}
		});
		JPanel deleteSalelinePanel = new JPanel();
		JPanel deleteSalelineInfoPanel = new JPanel();
		JPanel deleteSalelineChoicePanel = new JPanel();

		deleteSalelinePanel.setLayout(new BoxLayout(deleteSalelinePanel,
				BoxLayout.Y_AXIS));
		deleteSalelineInfoPanel.setLayout(new FlowLayout());
		deleteSalelineChoicePanel.setLayout(new FlowLayout());

		deleteSalelineWindow.getContentPane().add(deleteSalelinePanel);
		deleteSalelinePanel.add(deleteSalelineInfoPanel);
		deleteSalelinePanel.add(deleteSalelineChoicePanel);
		deleteSalelineInfoPanel.add(productBarcode);
		deleteSalelineInfoPanel.add(textField_ProductBarcode);
		deleteSalelineChoicePanel.add(btnDeleteSalelineOK);
		deleteSalelineChoicePanel.add(btnDeleteSalelineCancel);

		return deleteSalelineWindow;
	}

	// show offer saleline in the table
	private void showOfferSaleline(int offerId) {
		Sale offer;
		try {
			offer = saleCtr.getOffer(offerId);
			ArrayList<SalesLine> saleLines = offer.getSaleLines();
			saleLineTableModel.setRowCount(0);
			for (SalesLine saleline : saleLines) {
				saleLineTableModel.addRow(new Object[] { saleline.getBarcode(),
						saleline.getSaleItem().getName(),
						saleline.getQuantity(),
						saleline.getSaleItem().getsPrice(),
						saleline.getSaleItem().getTax(),
						saleline.getSubtotalWithoutDiscount() });
			}
		} catch (RealException e) {
			JOptionPane.showMessageDialog(null, e.toString(), "Error",
					JOptionPane.ERROR_MESSAGE);
		}
		addTotalPrice(offerId, saleLineTableModel);
	}

	private boolean saveOfferInfo(int offerId) {
		boolean success = true;
		try {
			try {
				saleCtr.updateSales(offerId, 2, textField_customerId.getText());
				saleCtr.updateSales(offerId, 1, textField_employeeId.getText());
			} catch (NumberFormatException e) {
				JOptionPane
						.showMessageDialog(
								null,
								"Please input number in customerId and employeeId field",
								"Error", JOptionPane.ERROR_MESSAGE);
			}
			// convert date
			saleCtr.updateSales(offerId, 3,
					String.valueOf(getDate(textField_date.getText())));
			if (rbnPickupYes.isSelected()) {
				saleCtr.noPickup(offerId, "");
				saleCtr.hasPickup(offerId);
			} else {
				saleCtr.noPickup(offerId, textField_deliveryAddress.getText());
			}

		} catch (RealException e) {
			success = false;
			JOptionPane.showMessageDialog(null, e.getError(), "Error",
					JOptionPane.ERROR_MESSAGE);
		} catch (ParseException e) {
			JOptionPane.showMessageDialog(null, "Field value invalid", "Error",
					JOptionPane.ERROR_MESSAGE);
		}
		return success;

	}

	private JPanel createOfferChoicePanel() {
		JPanel offerChoicePanel = new JPanel();
		offerChoicePanel.setLayout(new FlowLayout());

		if (loggedInPosition.equals("admin")
				|| loggedInPosition.equals("salesman")) {

			JButton btnEditOffer = new JButton("Edit");
			btnEditOffer.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					EditOfferActionPerformed(e);
				}
			});
			JButton btnCancelOrder = new JButton("Delete");
			btnCancelOrder.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					deleteOfferActionPerformed(e);
					textField_offerIdMenu.setText("");
				}
			});
			JButton btnConfirmPayment = new JButton("Confirm Offer");
			btnConfirmPayment.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					confirmOfferActionPerformed(e);
					showAllOffers();
					textField_offerIdMenu.setText("");
				}
			});
			offerChoicePanel.add(btnEditOffer);
			offerChoicePanel.add(btnCancelOrder);
			offerChoicePanel.add(btnConfirmPayment);
		}
		JButton btnBackOffer = new JButton("Back");
		btnBackOffer.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				showAllOffers();
				textField_offerIdMenu.setText("");
			}
		});
		offerChoicePanel.add(btnBackOffer);

		return offerChoicePanel;
	}

	private void confirmOfferActionPerformed(ActionEvent e) {
		int offerId = Integer.parseInt(textField_offerIdOrderInfo.getText());
		try {
			saleCtr.confirmOffer(offerId);
			JOptionPane.showMessageDialog(null, "The order is created",
					"Create Order", JOptionPane.INFORMATION_MESSAGE);
			((OrderUI) saleUI.getOrderUI()).showAllOrders();
		} catch (RealException e1) {

		}

	}

	private void deleteOfferActionPerformed(ActionEvent e) {
		int reply = JOptionPane.showConfirmDialog(null,
				"Are you sure you want to delete this Offer ?", "Delete Offer",
				JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
		if (reply == JOptionPane.YES_OPTION) {
			boolean success = true;
			try {
				saleCtr.removeSales(Integer.parseInt(textField_offerIdOrderInfo
						.getText()));
			} catch (NumberFormatException e1) {
				success = false;
				JOptionPane.showMessageDialog(null, "Field value invalid",
						"Error", JOptionPane.ERROR_MESSAGE);
			} catch (RealException e1) {
				success = false;
				JOptionPane.showMessageDialog(null, e1.getError(), "Error",
						JOptionPane.ERROR_MESSAGE);
			}
			if (success) {
				JOptionPane.showMessageDialog(null, "The Offer is deleted",
						"Delete Offer", JOptionPane.INFORMATION_MESSAGE);
				showAllOffers();
			}
		}
	}

	private void EditOfferActionPerformed(ActionEvent e) {
		showOfferEditInfoPanel();
	}

	// can edit offer info
	private void showOfferEditInfoPanel() {
		editOfferLeftPanel.removeAll();
		Sale offer;
		try {
			int offerId = Integer.parseInt((textField_offerIdOrderInfo.getText()));
			offer = saleCtr.getOffer(offerId);
			JPanel offerInfoPanel = createOfferEditInfoPanel(); // create
																// another panel
																// for offer
																// info editting

			textField_offerIdOrderInfo.setText(Integer.toString(offerId));
			setOfferInfo(offer);
			JPanel offerEditChoicePanel = creatOfferEditChoicePanel();

			editOfferLeftPanel.add(offerInfoPanel);
			editOfferLeftPanel.add(offerEditChoicePanel);

			editOfferSaleline(offerId);

			setOfferInfoEditable(true);

		} catch (RealException e1) {
		}

		CardLayout cl = (CardLayout) offerPanel.getLayout();
		cl.show(offerPanel, "editOfferInfoPanel");
	}

	// create offer edit info labels and buttons
	private JPanel createOfferEditInfoPanel() {

		JPanel offerEditInfoPanel = new JPanel();
		offerEditInfoPanel.setBorder(BorderFactory
				.createTitledBorder("Offer Info"));
		// GroupLayout gl = new GroupLayout(offerEditInfoPanel);
		// offerEditInfoPanel.setLayout(gl);
		// gl.setAutoCreateGaps(true);
		// gl.setAutoCreateContainerGaps(true);
		offerEditInfoPanel.setLayout(new GridLayout(1, 2));
		JPanel editOfferInfoLeftPanel = new JPanel();
		JPanel editOfferInfoRightPanel = new JPanel();
		editOfferInfoLeftPanel.setLayout(new BoxLayout(editOfferInfoLeftPanel,
				BoxLayout.Y_AXIS));
		editOfferInfoRightPanel.setLayout(new BoxLayout(
				editOfferInfoRightPanel, BoxLayout.Y_AXIS));

		JPanel customerIdPanel = new JPanel();
		customerIdPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
		customerIdPanel.add(lblCustomerId);

		JPanel employeeIdPanel = new JPanel();
		employeeIdPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
		employeeIdPanel.add(lblEmployeeId);

		JPanel datePanel = new JPanel();
		datePanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
		datePanel.add(lblDate);

		JPanel addressPanel = new JPanel();
		addressPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
		addressPanel.add(lblDeliveryAddress);

		JPanel pickupPanel = new JPanel();
		pickupPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
		pickupPanel.add(lblPickup);

		JPanel pickupPanel2 = new JPanel();
		JLabel space = new JLabel("");
		pickupPanel2.setLayout(new FlowLayout(FlowLayout.RIGHT));
		pickupPanel2.add(space);

		editOfferInfoLeftPanel.add(customerIdPanel);
		editOfferInfoLeftPanel.add(employeeIdPanel);
		editOfferInfoLeftPanel.add(datePanel);
		editOfferInfoLeftPanel.add(addressPanel);
		editOfferInfoLeftPanel.add(pickupPanel);
		editOfferInfoLeftPanel.add(pickupPanel2);

		textField_customerId = new JTextField();
		textField_employeeId = new JTextField();
		textField_date = new JTextField();
		textField_deliveryAddress = new JTextField();

		textField_customerId.setColumns(8);
		textField_employeeId.setColumns(8);
		textField_date.setColumns(8);
		textField_deliveryAddress.setColumns(8);

		bgPickup.add(rbnPickupYes);
		bgPickup.add(rbnPickupNo);

		JPanel customerIDFieldPanel = new JPanel();
		customerIDFieldPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
		customerIDFieldPanel.add(textField_customerId);

		JPanel employeeIdFieldPanel = new JPanel();
		employeeIdFieldPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
		employeeIdFieldPanel.add(textField_employeeId);

		JPanel dateFieldPanel = new JPanel();
		dateFieldPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
		dateFieldPanel.add(textField_date);

		JPanel addressFieldPanel = new JPanel();
		addressFieldPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
		addressFieldPanel.add(textField_deliveryAddress);

		JPanel yesRbnPanel = new JPanel();
		yesRbnPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
		yesRbnPanel.add(rbnPickupYes);

		JPanel noRbnPanel = new JPanel();
		noRbnPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
		noRbnPanel.add(rbnPickupNo);

		editOfferInfoRightPanel.add(customerIDFieldPanel);
		editOfferInfoRightPanel.add(employeeIdFieldPanel);
		editOfferInfoRightPanel.add(dateFieldPanel);
		editOfferInfoRightPanel.add(addressFieldPanel);
		editOfferInfoRightPanel.add(yesRbnPanel);
		editOfferInfoRightPanel.add(noRbnPanel);

		offerEditInfoPanel.add(editOfferInfoLeftPanel);
		offerEditInfoPanel.add(editOfferInfoRightPanel);

		/*
		 * gl.setHorizontalGroup(gl.createSequentialGroup()
		 * .addGroup(gl.createParallelGroup(GroupLayout.Alignment.LEADING)
		 * .addComponent(lblCustomerId) .addComponent(lblEmployeeId)
		 * .addComponent(lblDate) .addComponent(lblDeliveryAddress)
		 * .addComponent(lblPickup))
		 * .addGroup(gl.createParallelGroup(GroupLayout.Alignment.LEADING)
		 * .addComponent(textField_customerId)
		 * .addComponent(textField_employeeId) .addComponent(textField_date)
		 * .addComponent(textField_deliveryAddress) .addComponent(rbnPickupYes)
		 * .addComponent(rbnPickupNo)) );
		 * gl.setVerticalGroup(gl.createSequentialGroup()
		 * .addGroup(gl.createParallelGroup(GroupLayout.Alignment.BASELINE)
		 * .addComponent(lblCustomerId) .addComponent(textField_customerId))
		 * .addGroup(gl.createParallelGroup(GroupLayout.Alignment.BASELINE)
		 * .addComponent(lblEmployeeId) .addComponent(textField_employeeId))
		 * .addGroup(gl.createParallelGroup(GroupLayout.Alignment.BASELINE)
		 * .addComponent(lblDate) .addComponent(textField_date))
		 * .addGroup(gl.createParallelGroup(GroupLayout.Alignment.BASELINE)
		 * .addComponent(lblDeliveryAddress)
		 * .addComponent(textField_deliveryAddress))
		 * .addGroup(gl.createParallelGroup(GroupLayout.Alignment.BASELINE)
		 * .addComponent(lblPickup) .addComponent(rbnPickupYes))
		 * .addGroup(gl.createParallelGroup(GroupLayout.Alignment.LEADING)
		 * .addComponent(rbnPickupNo)) );
		 */

		setOfferInfoEditable(true);
		return offerEditInfoPanel;
	}

	private JScrollPane showSalelineTable() {
		saleLineTableModel = new DefaultTableModel() {
			private static final long serialVersionUID = 1L;

			@Override
			public boolean isCellEditable(int row, int column) {
				return false;
			}
		};
		saleLineTableModel.addColumn("Barcode");
		saleLineTableModel.addColumn("Product");
		saleLineTableModel.addColumn("Quantity");
		saleLineTableModel.addColumn("Sale Price");
		saleLineTableModel.addColumn("Tax");
		saleLineTableModel.addColumn("Subtotal Price");

		offerTableScrollPane = new JScrollPane();
		showSalelineTable = new JTable(saleLineTableModel);
		showSalelineTable.setAutoResizeMode(JTable.AUTO_RESIZE_NEXT_COLUMN);
		showSalelineTable.setAutoCreateRowSorter(true);

		offerTableScrollPane.setViewportView(showSalelineTable);
		return offerTableScrollPane;
	}

	private void addOfferTable() {
		offerTableModel = new DefaultTableModel() {
			private static final long serialVersionUID = 1L;

			@Override
			public boolean isCellEditable(int row, int column) {
				return false;
			}
		};
		offerTableModel.addColumn("ID");
		offerTableModel.addColumn("Customer");
		offerTableModel.addColumn("Group");
		offerTableModel.addColumn("Date");
		offerTableModel.addColumn("Total Price");

		offerTableScrollPane = new JScrollPane();
		showAllOffersPanel.add(offerTableScrollPane);
		showAllOffersTable = new JTable(offerTableModel);
		showAllOffersTable.setAutoResizeMode(JTable.AUTO_RESIZE_NEXT_COLUMN);
		showAllOffersTable.setAutoCreateRowSorter(true);

		showAllOffersTable.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				int row = showAllOffersTable.rowAtPoint(e.getPoint());
				if (e.getClickCount() == 2) {
					if (showOffer(Integer.valueOf((Integer) showAllOffersTable
							.getValueAt(row, 0)))) {
					}
				}
			}
		});
		offerTableScrollPane.setViewportView(showAllOffersTable);
	}

	private void showAllOffers() {

		ArrayList<Sale> sales = SalesRecords.getInstance().getSalesRecords();
		offerTableModel.setRowCount(0);
		for (Sale offer : sales) {
			if (offer.getStatus() == Status.Offer) {
				try {
					offerTableModel
							.addRow(new Object[] {
									offer.getId(),
									offer.getCustomer().getName(),
									offer.getCustomer().getGroup().getId(),
									offer.getDate(),
									Double.valueOf(new DecimalFormat("#.##").format(offer
											.getTotalPriceWithDiscount())) });
				} catch (RealException e) {
					JOptionPane.showMessageDialog(null, e.getError(), "Error",
							JOptionPane.ERROR_MESSAGE);
				}
			}
		}
		CardLayout cl = (CardLayout) offerPanel.getLayout();
		cl.show(offerPanel, "showAllOffersPanel");
	}

	public void addTotalPrice(int offerId, DefaultTableModel tableModel) {
		String totalPrice = "";

		double price = 0;
		double discount = 0;
		try {
			price = saleCtr.getOffer(offerId).getTotalPriceWithDiscount();
			discount = saleCtr.getOffer(offerId).getTotalPriceWithoutDiscount();
		} catch (RealException e) {
			JOptionPane.showMessageDialog(null, e.getError(), "Error",
					JOptionPane.ERROR_MESSAGE);
		}
		if (price != 0.0) {
			totalPrice = Double.toString(Double.valueOf(new DecimalFormat(
					"#.##").format(price)));
		} else {
			totalPrice = Double.toString(price);
		}
		String[] space = { "", "", "", "", "", "" };
		String[] discountRow = { "", "", "", "", "Discount:", Double.toString(Double.valueOf(new DecimalFormat(
				"#.##").format(price - discount)))};
		String[] totalPriceRow = { "", "", "", "", "Total Price:", totalPrice };
		tableModel.addRow(space);
		tableModel.addRow(space);
		tableModel.addRow(discountRow);
		tableModel.addRow(totalPriceRow);
	}

	private int getTextFieldId(JTextField textField) {
		int id = 0;
		try {
			id = Integer.parseInt(textField.getText());
		} catch (NumberFormatException e) {
			JOptionPane.showMessageDialog(null, "Please input number", "Error",
					JOptionPane.ERROR_MESSAGE);
		}

		return id;
	}

	public long getCurrentDate() {
		Calendar cal = Calendar.getInstance();
		java.util.Date utilDate = cal.getTime();
		return utilDate.getTime();
	}

	// convert date from long to string type
	public String convertDate(long date) {
		String orderDate = new SimpleDateFormat("dd/MM/yyyy").format(new Date(
				date));
		return orderDate;
	}

	public long getDate(String input) throws ParseException, RealException {
		SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
		formatter.setLenient(false);
		java.util.Date utilDate = null;
		utilDate = formatter.parse(input);
		if (!formatter.format(utilDate).equals(input))
			throw new RealException("Field value invalid");
		return utilDate.getTime();
	}

}
